<template>
  <div class="purchase-quotation-list">
    <!-- 添加查询条件 -->
    <view v-show="!previewVisible">
      <a-card :bordered="false" class="header-search-card card-wrapper" bodyStyle="padding: 0.3vw 1.2vw 0.2vw;">
        <a-form
          :model="searchParams"
          layout="inline"
          class="search-form"
        >
          <div class="search-container">
            <div class="search-fields">
              <div class="search-item">
                <label class="search-label">料号:</label>
                <div class="search-input">
                  <a-input
                    v-model:value="searchParams.pmaauc001"
                    placeholder=""
                    allow-clear
                    size="small"
                  />
                </div>
              </div>

              <div class="search-item">
                <label class="search-label">品名:</label>
                <div class="search-input">
                  <a-input
                    v-model:value="searchParams.pmaauc002"
                    placeholder=""
                    allow-clear
                    size="small"
                  />
                </div>
              </div>
            </div>

            <div class="search-item search-buttons-inline">
              <a-button type="primary" @click="handleSearch" size="small">
                <template #icon>
                  <SearchOutlined />
                </template>
                查询
              </a-button>
              <a-button type="primary" @click="handleReset" size="small">
                <template #icon>
                  <RedoOutlined />
                </template>
                重置
              </a-button>

            </div>
          </div>
        </a-form>
      </a-card>
    </view>

    <!-- 加载中提示 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-content">
        <a-spin size="large" />
        <p class="loading-text">数据加载中...</p>
      </div>
    </div>

    <a-card title="" :bordered="false" headStyle="min-height: 2.08vw;" bodyStyle="padding: 0.8vw 1.25vw;">
      <div class="table-container">
        <SortableTable
          :data="paginatedData"
          :columns="columns"
          :row-height="'1.67vw'"
          :font-size="'0.9vw'"
          :show-sort-indicators="true"
          :sorted-indicator-color="'#fff'"
          :unsorted-indicator-color="'rgba(255, 255, 255, 0.5)'"
          @sort-change="handleSortChange"
          :sticky-header="true"
          :fixed-action="true"
          :get-row-class="getRowClass"
          @row-dblclick="handleRowDblClick"
          v-show="!loading"
        >
          <template #column-index="{ index }">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>

          <template #column-selection="{ item }">
            <a-checkbox
              :checked="selectedRows.some(row => row.pmaauc001 === item.pmaauc001)"
              @change="(e) => handleRowSelection(e, item)"
              @click.stop
            />
          </template>
        </SortableTable>

        <!-- 无数据提示 -->
        <div v-if="paginatedData.length === 0 && !loading" class="no-data">
          暂无数据
        </div>
      </div>

      <div class="pagination-wrapper">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="true"
          :page-size-options="pagination.pageSizeOptions"
          @change="handlePageChange"
          @show-size-change="handlePageSizeChange"
        />
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { SortableTable } from '@/components/custom';
import { useRouterPush } from '@/hooks/common/router';
import dayjs from 'dayjs';
import { getMaterialPriceListApi } from '@/service/api/modules/purchase';
// 导入图标组件
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';


const { routerPushByKey } = useRouterPush();

// 添加loading状态
const loading = ref(false);

// 查询参数
const searchParams = reactive({
  pmaauc001: null,    // 料号
  pmaauc002: null     // 品名
});

// 选中的行
const selectedRows = ref([]);

// 表格列定义
const columns = [
  {
    key: 'selection',
    label: '',
    width: '3vw'
  },
  {
    key: 'index',
    label: '序号',
    width: '3.125vw'
  },
  {
    key: 'pmaaucsite',
    label: '据点',
    width: '6.25vw'
  },
  {
    key: 'pmaauc001',
    label: '料号',
    width: '8vw'
  },
  {
    key: 'pmaauc002',
    label: '品名',
    width: '12vw'
  },
  {
    key: 'pmaauc003',
    label: '规格',
    width: '12vw'
  },
  // {
  //   key: 'pmaauc012',
  //   label: '税种',
  //   width: '6vw'
  // },
  {
    key: 'oodbl004',
    label: '税种说明',
    width: '10vw'
  },
  // {
  //   key: 'pmaauc013',
  //   label: '税率',
  //   width: '6vw'
  // },
  {
    key: 'pmaauc004',
    label: '基准价',
    width: '6vw'
  },
  {
    key: 'pmaauc006',
    label: '单位',
    width: '6vw'
  },
  {
    key: 'pmdt036',
    label: '采购单价',
    width: '6vw'
  },
  {
    key: 'pmdsdocdt',
    label: '最早采购日期',
    width: '10vw'
  },
  {
    key: 'pmdsdocdta',
    label: '最近采购日期',
    width: '10vw'
  },

];

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 100,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
});

// 分页数据
const paginatedData = computed(() => {
  return tableData.value;
});

// 自定义行类名函数，用于添加行点击样式
const getRowClass = (index) => {
  const baseClass = index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
  return baseClass;
};

// 处理排序变化
const handleSortChange = (sortState) => {
  console.log('排序状态:', sortState);
};

// 处理行双击事件
const handleRowDblClick = (item, index) => {
  console.log('双击行数据:', item);
  // 可以在这里添加行双击后的处理逻辑，例如跳转到详情页
};

// 处理分页变化
const handlePageChange = (page, pageSize) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  getMaterialPriceList();
};

// 处理页面大小变化
const handlePageSizeChange = (current, size) => {
  pagination.current = current;
  pagination.pageSize = size;
  getMaterialPriceList();
};

// 查询方法
const handleSearch = () => {
  pagination.current = 1;
  getMaterialPriceList();
};

// 重置方法
const handleReset = () => {
  searchParams.pmaauc001 = null;
  searchParams.pmaauc002 = null;
  handleSearch();
};

// 处理行选择
const handleRowSelection = (e, record) => {
  const checked = e.target.checked;
  if (checked) {
    // 添加到选中项
    selectedRows.value.push(record);
  } else {
    // 从选中项中移除
    const index = selectedRows.value.findIndex(row => row.pmaauc001 === record.pmaauc001);
    if (index > -1) {
      selectedRows.value.splice(index, 1);
    }
  }
};

// 新增方法
const handleAdd = () => {
  // 跳转到新增页面
  routerPushByKey('purchase_quotation-add');
};

// 编辑方法
const handleEdit = () => {
  if (selectedRows.value.length !== 1) {
    message.warning('请选择一条数据进行编辑');
    return;
  }

  const record = selectedRows.value[0];
  // 跳转到编辑页面，传递选中记录的参数
  routerPushByKey('purchase_quotation-edit', {
    query: {
      id: record.id,
      // 可根据实际需求传递更多参数
    }
  });
};

// 删除方法
const handleDelete = () => {
  if (selectedRows.value.length !== 1) {
    message.warning('请选择一条数据进行删除');
    return;
  }

  const record = selectedRows.value[0];

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除料号为 ${record.pmaauc001} 的记录吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      // 这里应该调用实际的删除接口
      // 由于目前没有看到删除接口，暂时只给出提示
      message.success('删除成功');
      // 实际项目中，应该在这里调用删除接口，然后刷新列表
      // 删除完成后重新加载数据
      getMaterialPriceList();
    }
  });
};

// 获取采购报价列表
const getMaterialPriceList = () => {
  loading.value = true;

  const params = {
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    ...searchParams
  };

  // 修复日期参数格式问题
  if (params.createDate && typeof params.createDate === 'object' && params.createDate.$d) {
    // 如果是 dayjs 对象，转换为标准日期字符串格式
    params.createDate = dayjs(params.createDate.$d).format('YYYY-MM-DD');
  } else if (params.createDate === null || params.createDate === undefined || params.createDate === '') {
    // 如果日期为空，确保传递 null 值
    params.createDate = null;
  }

  console.log('查询参数:', params);

  getMaterialPriceListApi(params).then(res => {
    const data = res.otherData;
    console.log('接口返回数据:', data);
    if (data.code === 200) {
      tableData.value = data.rows || [];
      pagination.total = data.total || 0;
    }
  }).finally(() => {
    loading.value = false;
  });
};

onMounted(() => {
  getMaterialPriceList();
});
</script>

<style scoped>
.search-container {
  display: flex;
  width: 100%;
  align-items: center;
  gap: 0.5vw;
}

.search-fields {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(12vw, 1fr));
  gap: 0.5vw;
  flex: 1;
}

.search-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  min-width: 0;
}

.search-label {
  font-size: 0.8vw;
  margin-bottom: 0;
  margin-right: 0.2vw;
  color: #000000;
  white-space: nowrap;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  min-width: 0;
}

.search-buttons-inline {
  display: flex;
  gap: 0.3vw;
  align-items: end;
  height: 1.8vw;
  margin-left: auto;
}

:deep(.ant-input) {
  font-size: 0.8vw;
  height: 1.8vw;
}

:deep(.ant-select) {
  font-size: 0.8vw;
}

:deep(.ant-select-selector) {
  height: 1.8vw !important;
  align-items: center !important;
}

:deep(.ant-select-selection-item) {
  line-height: 1.6vw !important;
  align-items: center !important;
}

:deep(.ant-picker) {
  font-size: 0.8vw;
  height: 1.8vw;
  padding: 0 0.6vw;
  display: flex;
  align-items: center;
}

:deep(.ant-picker-input > input) {
  height: 1.6vw;
}

:deep(.ant-btn) {
  font-size: 0.8vw;
  height: 1.8vw;
  padding: 0 0.5vw;
  border-radius: 0.2vw;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: none;
}

/* 修改查询按钮和导出、编辑按钮选中后的背景色为#66CFB6 */
:deep(.ant-btn-primary) {
  background-color: #5F9EA0;
  border-color: #5F9EA0;
  box-shadow: none;
}

.purchase-quotation-list {
  padding: 0.2vw 0.4vw;
  border-radius: 0.21vw;
  height: calc(100vh - 5.5vw);
  display: flex;
  flex-direction: column;
}

:deep(.ant-card) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.ant-card-body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.pagination-wrapper {
  margin-top: 0.52vw;
  display: flex;
  justify-content: flex-end;
}

.no-data {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #999;
  font-size: 0.73vw;
}

/* 可点击行的样式 */
.clickable-row {
  cursor: pointer;
}

.clickable-row:hover {
  background-color: #e6f7ff !important;
}

.header-search-card {
  margin-bottom: 0.5vw;
}

/* 响应式处理 */
@media (max-width: 1200px) {
  .search-container {
    flex-direction: column;
    align-items: stretch;
  }

  .search-fields {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    margin-bottom: 0.5vw;
  }

  .search-buttons-inline {
    margin-left: 0;
    justify-content: flex-start;
  }

  .purchase-quotation-list {
    flex-direction: column;
  }

  .purchase-quotation-list .left-panel,
  .right-panel {
    flex: 1;
    padding: 0;
  }

  .purchase-quotation-list .left-panel {
    padding-right: 0;
  }

  .right-panel {
    border-left: none;
    border-top: 1px solid #f0f0f0;
    margin-top: 1vw;
    padding-top: 1vw;
  }
}

@media (max-width: 768px) {
  .search-fields {
    grid-template-columns: 1fr;
  }
}

/* 按钮图标上下对齐 */
:deep(.ant-btn) {
  font-size: 0.8vw;
  height: 1.8vw;
  padding: 0 0.5vw;
  border-radius: 0.2vw;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: none;
}

/* 加载状态样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  border-radius: 0.21vw;
}

.loading-content {
  text-align: center;
}

.loading-text {
  margin-top: 0.5vw;
  font-size: 0.8125vw;
  color: #666;
}
</style>
